/**
 * 测试自己编写的中间件原理是否成功
 * 以及学习使用 express 中间件的使用
 * 
 * express中间件的三中使用方法
 * 1: app.use((req, res, next) => { // 一旦注册后就会被使用
 *      // to do 
 *      next()
 * })
 * 
 * 2: app.use('/api', (req, res, next) => { // req.url 是 '/api' 开头时才会调用该中间件
 *      // to do 
 *      next()
 * })
 * 
 * 2: app.use((req, res, next) => { // 可以在 use 中注册多个中间件
 *      // to do
 *      next()
 * }, (req, res, next) => {
 *      // to do 
 *      next()
 * })
 */

const http = require('http')
const express = require('./express')

const app = express()

app.use((req, res, next) => {
    console.log('处理cookie')
    next()
}, (req, res, next) => {
    console.log('二次处理cookie')
    next()
})

app.use((req, res, next) => {
    setTimeout(() => {
        console.log('处理body')
        req.body = {
            username: 'jacob',
            password: '123'
        }
        next()
    }, 1000)
})

app.use((req, res, next) => {
    console.log('返回数据')
    next()
})

app.use('/login', (req, res, next) => {
    console.log('登录成功')
    res.end(
        JSON.stringify(req.body)
    )
})

app.use((req, res, next) => {
    console.log('404 not found')
    res.end('404 not found')
})

app.use((err, req, res, next) => {
    console.log('err handler')
    res.end('err handler' + JSON.stringify(err))
})

http.createServer(app).listen('3000', () => {
    console.log('server is running on port 3000')
})

